import React, { useEffect, useState, useRef, createElement } from 'react'
import { List, Avatar, Image, message, Button, Modal, Input, Space, Upload, Popover, Cascader, Tooltip, Popconfirm, Row, Col } from 'antd';
import { DeleteTwoTone, EditTwoTone } from '@ant-design/icons';
import axios from 'axios';
import GoodsCascader from '../../../components/GoodsCascader'
import moment from 'moment'
import { useNavigate } from 'react-router-dom'
import myprovinceData from '../../../js/provinceData';
export default function Index() {
    const loginUser = JSON.parse(localStorage.getItem("loginUser"));
    let editChangeInfo = {};
    const navigate = useNavigate()
    const [listData, setListData] = useState([]);
    const [listDataBac, setListDataBac] = useState([]); //存一份获取的数据用于筛选
    const [visible2, setVisible2] = useState(false);
    const titleRef2 = useRef()
    const messageRef2 = useRef()
    const [chaninfoId, setchaninfoId] = useState('');
    useEffect(() => {
        axios.get("http://localhost:8080/qryAllChangeXme?id=" + loginUser.id).then(resp => {

            setListData(resp.data.data);
            setListDataBac(resp.data.data)

        })
        return () => {
        };
    }, []);

    const filterByGoods = (value) => {

        if (value) { //如果筛选了 执行
            let lastIndex = value.length - 1
            console.log("baclistdata", listDataBac);
            setListData(listDataBac)
            let rs = value[lastIndex]
            console.log("筛选物品:", value);
            console.log("最终筛选物品str", rs);
            const newListData = listDataBac.filter(item => item.mytype === rs)
            console.log("物品类别筛选后的结果:", newListData);
            setListData(newListData)
        } else { //点击X后就是undefined把备份的listdata赋回去
            setListData(listDataBac)
        }

    }
    const filterCity = (value) => {
        console.log(value);
        if (value) { //如果筛选了 执行
            console.log("baclistdata", listDataBac);
            setListData(listDataBac)
            let rs = "";
            for (let i = 0; i < value.length; i++) {
                rs += value[i];
            }
            console.log("筛选物品:", value);
            console.log("最终筛选物品str", rs);
            const newListData = listDataBac.filter(item => item.city === rs)
            console.log("物品类别筛选后的结果:", newListData);
            setListData(newListData)
        } else { //点击X后就是undefined把备份的listdata赋回去
            setListData(listDataBac)
        }
    }
    const deleteChange = (id) => {
        console.log("要删除的id:", id);
        axios.post("http://localhost:8080/deleteChangeInfo?id=" + id).then(resp => {
            if (resp.data.state === "0") {
                message.success(resp.data.message, 1);
                setTimeout(() => {
                    window.location.reload()
                }, 800);
            }
        })
    }
    const showModal = (id) => {   //修改物品信息的modal
        setVisible2(true);
        // editChangeInfo.id = id;
        setchaninfoId(id)
        titleRef2.current.state.value = '';
        messageRef2.current.resizableTextArea.textArea.value = '';
        console.log(editChangeInfo);
    };
    const handleOk2 = () => {
        editChangeInfo.title = titleRef2.current.state.value || null;
        editChangeInfo.message = messageRef2.current.resizableTextArea.textArea.value || null;
        editChangeInfo.id = chaninfoId;
        console.log("修改后物品信息:", editChangeInfo);
        setVisible2(false)
        axios.post("http://localhost:8080/updateChangeInfo", editChangeInfo).then(resp => {
            if (resp.data.state === "0") {
                message.success(resp.data.message, 1)
                setTimeout(() => {
                    window.location.reload()
                }, 1000);

            } else {
                message.error(resp.data.message, 1)
                setTimeout(() => {
                    window.location.reload()
                }, 1000);
            }

        }).catch(err => {
            message.error("请求超时!", 1);
            setTimeout(() => {
                window.location.reload()
                seteditVisible(false);
            }, 1000);
        })

    };
    const handleCancel2 = () => {
        setVisible2(false)
        titleRef2.current.state.value = '';
        messageRef2.current.state.value = '';
        setchaninfoId('')
        editChangeInfo = {}
    }
    const mytypeChange2 = (value) => {
        let lastIndex = value.length - 1
        let rs = value[lastIndex]

        console.log(rs);
        editChangeInfo.mytype = rs;
    }

    const wanttypeChange2 = (value) => {
        let lastIndex = value.length - 1
        let rs = value[lastIndex]
        console.log(rs);
        editChangeInfo.wanttype = rs;
    }
    const photoupdate = (info) => {
        if (info.file.status === 'done') {
            message.success(`${info.file.name}图片上传成功`);
            setTimeout(() => {
                window.location.reload()
            }, 500);
        } else if (info.file.status === 'error') {
            message.error(`图片上传失败,尝试更换另一张jpg图片`);
        }

    }
    const beforeUpload = (file) => {
        console.log(file.size);
        if (file.size > (2097152)) {
            console.log("图片超过2M");
            message.error(`图片不得超过2M`);
            return Upload.LIST_IGNORE;
        } else {
            return true;
        }
    }
    return (
        <div className="animate__animated animate__fadeIn">
            <div style={{ margin: 20, display: 'flex' }}>
                <GoodsCascader onChange={filterByGoods} title="物品类别筛选" />
                <Cascader placeholder={"城市"} onChange={filterCity} options={myprovinceData} defaultValue={''} style={{ marginLeft: 20 }} />
            </div>
            <List
                itemLayout="vertical"
                size="large"
                pagination={{
                    onChange: page => {
                        console.log(page);
                    },
                    pageSize: 3,
                }}
                dataSource={listData}

                renderItem={item => (
                    <List.Item
                        key={item.id}
                        actions={[
                            <Button type="primary" onClick={() => { showModal(item.id) }}>编辑<EditTwoTone /></Button>,
                            <Popconfirm
                                title="删除?"
                                onConfirm={() => { deleteChange(item.id) }}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button danger type="primary"> 删除<DeleteTwoTone twoToneColor="red" /></Button>
                            </Popconfirm>

                        ]}
                        // extra={
                        //     <Image
                        //         width={135}
                        //         height={135}
                        //         src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                        //         fallback=""
                        //     //无图片时显示
                        //     />
                        // }
                        extra={
                            <Space direction="vertical">
                                <Popover placement="topLeft" content={'点击修改图片'}>
                                    <Upload maxCount={1} action={`http://localhost:8080/saveChangeInfoPhoto?id=${item.id}`} beforeUpload={beforeUpload} onChange={photoupdate}>
                                        <Image

                                            preview={false}
                                            width={135}
                                            height={135}
                                            src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                                        />
                                    </Upload>
                                </Popover>
                            </Space>
                        }
                    >
                        <List.Item.Meta
                            avatar={<Avatar src={`http://localhost:8080/getUserHead?id=${item.createrid}`} />}//头像
                            title={`${item.title}`}
                            description={moment(Number(item.createtime)).format('YYYY-MM-DD HH:mm:ss')}
                        />
                        {item.message}

                    </List.Item>
                )}

            />
            <Modal
                title="修改信息"
                visible={visible2}
                onOk={handleOk2}
                onCancel={handleCancel2}
                // width={'30%'}
                centered={true}
            >
                <Row justify="center">
                    <Col>
                        <GoodsCascader title="我的旧物类别" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={mytypeChange2} />
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <GoodsCascader title="想要的类别" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={wanttypeChange2} />
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <Input placeholder="创建标题" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={titleRef2}></Input>
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <Input.TextArea style={{ width: '1.7REM', marginTop: '0.03REM' }} placeholder="具体描述" ref={messageRef2} />
                    </Col>
                </Row>
            </Modal>
        </div>
    )
}
